<?php

function flatten_GP_array(array $var,$prefix = false){
        $return = array();
        foreach($var as $idx => $value){
                if(is_scalar($value)){
                        if($prefix){
                                $return[$prefix.'['.$idx.']'] = $value;
                        } else {
                                $return[$idx] = $value;
                        }
                } else {
                        $return = array_merge($return,flatten_GP_array($value,$prefix ? $prefix.'['.$idx.']' : $idx));
                }
        }
        return $return;
}


// Allowed hostnames
//THERE HAS TO BE A BETTER WAY TO DO THIS
$allowed_hosts = array('nickpettazzoni.com', 'allthequestions.com', 'comicftw.tumblr.com');

//check if it's one of these
preg_match('@^(?:http://)?([^/]+)@i', $_REQUEST['path'], $matches);
$host = $matches[1];

if(!in_array($host, $allowed_hosts)){
	echo 'failure';
	exit();
}

// Get the REST call path from the AJAX application
// Is it a POST or a GET?
$path = ($_POST['path']) ? $_POST['path'] : $_GET['path'];
$url = $path;


/*debug
if($_GET['path'])
echo 'GET: ' . $path . "\n";
*/

// If it's a GET, serialize!
if ($_GET['path']) {
	$getvars = '?';
	while ($element = current($_GET)) {
		if(key($_GET) != 'host' && key($_GET) != 'path'){
			$getvars .= key($_GET).'='.$element.'&';
		}
		next($_GET);
	}
	//debug
	//echo "getvars: " . $getvars . "\n";

	$url .= $getvars;
	
	//debug
	//echo "url: " . $url . "\n";
}

// Open the Curl session
$session = curl_init($url);

// If it's a POST, put the POST data in the body
if ($_POST['path']) {
	curl_setopt ($session, CURLOPT_POST, true);
	curl_setopt ($session, CURLOPT_POSTFIELDS, flatten_GP_array($_POST));
}

// Don't return HTTP headers. Do return the contents of the call
curl_setopt($session, CURLOPT_HEADER, false);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);

// Make the call
$xml = curl_exec($session);

//header("Content-Type: text/xml");

echo $xml;
curl_close($session);

?>
